let d = null;
let app = getApp()
const db = wx.cloud.database({
  env: app.globalData.CLOUD_ENV
})
// 获取操作面试题数据表的对象（面试题数据集合）
const DBInterview = db.collection('db_topic')
const DBLike = db.collection('db_like')
const DBCorrection= db.collection('db_correction')
// 定义数组记录当前分类所有面试题
let topic_all_arr = [];
let index = 0;
let delay = null;
Page({
  data: {
    startX: 0,
    startY: 0,
    x: 0,
    y: 0,
    transitionValue: 'none',
    isLike: false,
    // 存在面试题的数据（3个）
    arr: [],
    // 索引
    index: 0,
    id: '',
    len: 0,
    isShow: true,
    num: 2,
    boxShadow: '',
    rid: '',
    rq: '',
    rtext:'',
    rtype:'',
    show: false,
    message: '',
    ra:'',
    topic_all_arr
  },

  setIndexFn(e){
    // console.log(e.detail.current)
    this.setData({
      index: e.detail.current
    })
  },
  // 跳转主页
  toHome() {
    wx.switchTab({
      url: '../index/index',
    })
  },
  // 手指按下的行为
  startFn(event) {
    index = this.data.index;
    //  console.log(event.changedTouches[0].pageX)
    this.setData({
      // 记录手指按下在页面的X坐标和Y坐标
      startX: event.changedTouches[0].pageX,
      startY: event.changedTouches[0].pageY,
      // 移除过渡属性值
      transitionValue: 'none',
      // 初始化x和y坐标（left和top属性）
      x: 0,
      y: 0
    })
  },
  // 手指滑动的行为
  moveFn(event) {
    let moveX = event.changedTouches[0].pageX
    let moveY = event.changedTouches[0].pageY
    let v = moveX - this.data.startX;
    if (v < 0) {
      this.setData({
        boxShadow: 'bs-1'
      })
    } else {
      this.setData({
        boxShadow: 'bs-2'
      })
    }
    // console.log({v})
    // 记录卡片的left和top属性值
    let x = moveX - this.data.startX;
    let y = moveY - this.data.startY;
    // if (y < -150) y = -150;
    // if (y > 150) y = 150;
    // console.log({x,y});
    this.setData({
      x,
      y: 0,
      transitionValue: 'none'
    })
  },
  // 手指松开的行为
  endFn() {
    // 获取x坐标
    let x = this.data.x;
    // 判断滑动的距离是否超过100像素 
    if (Math.abs(x) > 100) {
      // 防抖
      if (d != null) {
        clearTimeout(d)
      }
      // 负数（向左）
      if (x < 0) {
        // arr 是渲染3个卡片的数组
        let arr = this.data.arr;
        arr.shift()
        this.setData({
          x: -400,
          transitionValue: 'all  .5s'
        })
        // 填充题目(向左滑动切换下一题)
        index++;
        d = setTimeout(() => {
          if (index > topic_all_arr.length - 1) {
            index = topic_all_arr.length - 1;
            wx.showToast({
              title: '这最后一题了',
              icon: 'none'
            })
          }
          let arr = topic_all_arr.slice(index, index + 3)
          this.setData({
            x: 0,
            y: 0,
            arr,
            transitionValue: 'none',
            index,
            rid: topic_all_arr[index]._id,
            rq: topic_all_arr[index].q,
            rtext: topic_all_arr[index].text,
            rtype: topic_all_arr[index].type
          })
          clearTimeout(d)
          d = null
        }, 300)
      }
      // 正数（向右）
      else {
        let arr = this.data.arr;
        arr.pop()
        this.setData({
          x: 400,
          transitionValue: 'all  .5s'
        })
        // 填充题目(向右滑动切换上一题)
        index--;
        d = setTimeout(() => {
          if (index < 0) {
            index = 0;
            wx.showToast({
              title: '这是第一题了',
              icon: 'none'
            })
          }
          let arr = topic_all_arr.slice(index, index + 3)
          this.setData({
            x: 0,
            y: 0,
            arr,
            transitionValue: 'none',
            index,
            rid: topic_all_arr[index]._id,
            rq: topic_all_arr[index].q,
            rtext: topic_all_arr[index].text,
            rtype: topic_all_arr[index].type
          })
          clearTimeout(d)
          d = null
        }, 300)
      }
    } else {
      this.setData({
        x: 0,
        y: 0,
        transitionValue: 'all  .5s'
      })
    }

    this.setData({
      boxShadow: ''
    })
  },
  // 点击收藏题目
  sendLike(e) {
    let {
      isLike,
      id
    } = e.detail;
    let arr = this.data.topic_all_arr.map(item => {
      if (item._id == id) {
        item.isLike2 = isLike
      }
      return item;
    })
    // console.log(isLike,id)
    this.setData({
      topic_all_arr: arr
    })

    let key = this.data.key;
    wx.setStorageSync(key, JSON.stringify(topic_all_arr))
  },

  // 获取分类列表
  async getInterviewFn(text) {
    wx.showLoading({
      title: '正在加载...',
    })
    let openid = wx.getStorageSync('openid')
    let res = await DBInterview.where({
      text
    }).count()
    let count = res.total;
    let all = [];
    for (let i = 0; i < count; i += 20) {
      await DBInterview.where({
          text
        }).skip(i).get()
        .then(
          content => {
            let {
              data
            } = content;
            if (data.length != 0) {
              let arr = data.map(item => {
                let obj = {
                  ...item
                }
                obj.date = util.formatTime(item.create_time)
                return obj;
              })
              all = all.concat(arr)
            }
          }
        )
    }

    // 记录当前分类所有题目
    topic_all_arr = all
   

    this.setData({
      lists: topic_all_arr,
      topic_all_arr 
    })

    // 执行后续
    for (let i = 0; i < topic_all_arr.length; i++) {
      if (topic_all_arr[i]._id == this.data.id) {
        index = i;
      }
      // 判断每个题目是否被当前用户收藏了
      await DBLike.where({
        id: topic_all_arr[i]._id,
        openid
      }).get().then(
        result => {
          // 判断当前题目是否被收藏了
          if (result.data.length == 1) {
            topic_all_arr[i].isLike2 = true;
          } else {
            topic_all_arr[i].isLike2 = false;
          }
        }
      )
      // 换行符的正则表达式 /\\n/
      // topic_all_arr[i].result = topic_all_arr[i].a.split(/\\n/);
      // topic_all_arr[i].topic_codes =  topic_all_arr[i].topic_code && topic_all_arr[i].topic_code.split(/\\n/);
      topic_all_arr[i].result = topic_all_arr[i].a
      topic_all_arr[i].topic_codes =  topic_all_arr[i].topic_code 
    }
    this.setData({
      index,
      topic_all_arr
    })
    // console.log('topic_all_arr',this.data.topic_all_arr)
    if (topic_all_arr.length == 0) return;
    let key = this.data.key;
    let startTime = this.data.startTime;
    wx.setStorageSync(key, JSON.stringify(topic_all_arr))
    wx.setStorageSync(startTime, new Date().getTime())
    wx.hideLoading();
  },

  // 加载页面执行的回调函数
  onLoad(options) {
    // 获取从分类携带的分类名称和id
    if(options){
        let {
          id,
          text,
          key
        } = options;
        if (id) {
    
          // 记录id
          this.setData({
            id,
            key,
            rid: id
          })
        } else {
          wx.redirectTo({
            url: '../classify/classify',
          })
        }
    
        if (key) {
          let data = wx.getStorageSync(key);
          if (data) {
            topic_all_arr = JSON.parse(data)
            index = 0;
            for (var i = 0; i < topic_all_arr.length; i++) {
              if (topic_all_arr[i]._id == id) {
                index = i;
                break;
              }
            }
            this.setData({
              arr: topic_all_arr.slice(index, index + 3),
              index: index,
              len: topic_all_arr.length,
              rid: id ,
              rq: topic_all_arr[index].q ,
              rtext: topic_all_arr[index].text,
              rtype: topic_all_arr[index].type,
              topic_all_arr 
            })
            // console.log(topic_all_arr)
          } else {
            // 获取所有分类题目
            this.getInterviewFn(text);
          }
        } else {
          wx.redirectTo({
            url: '../classify/classify',
          })
        }
    }
    else {
       wx.navigateBack();
    }
    // console.log({index,topic_all_arr})
  },
  // 是否显示答案
  showFn() {
    this.setData({
      isShow: true,
      num: 2
    })
  },
  hideFn() {
    this.setData({
      isShow: false,
      num: 1
    })
  },
  toNext() {
    // 防抖
    if (d != null) {
      clearTimeout(d)
    }
    // 填充题目(向左滑动切换下一题)
    let index = this.data.index;
    index ++;
    d = setTimeout(() => {
      if (index > topic_all_arr.length - 1) {
        index = topic_all_arr.length - 1;
        wx.showToast({
          title: '这最后一题了',
          icon: 'none'
        })
      }
      this.setData({
        index,
        rid: topic_all_arr[index]._id,
        rq: topic_all_arr[index].q,
        rtext: topic_all_arr[index].text,
        rtype: topic_all_arr[index].type,
        topic_all_arr
      })
      clearTimeout(d)
      d = null
    }, 50)
  },
  toPrev() {
    // 防抖
    if (d != null) {
      clearTimeout(d)
    }
    let index = this.data.index;
    // 填充题目(向右滑动切换上一题)
    index--;
    d = setTimeout(() => {
      if (index < 0) {
        index = 0;
        wx.showToast({
          title: '这是第一题了',
          icon: 'none'
        })
      }
      this.setData({
        index,
        rid: topic_all_arr[index]._id,
        rq: topic_all_arr[index].q,
        rtext: topic_all_arr[index].text,
        rtype: topic_all_arr[index].type
      })
      clearTimeout(d)
      d = null
    }, 50)
  },
  toModifiyFn(e){
    // console.log(e.currentTarget.dataset)
    let {rid, rq, rtext, rtype} = e.currentTarget.dataset;
    let openid = wx.getStorageSync('openid')
    if(openid){
      this.setData({ show: true , rid , rq , rtext, rtype});
    }
    else {
      wx.showToast({
        title: '请先登录...',
        icon: 'none'
      })
    }
  },
  toSubmitRa(){

    if(delay != null) {
      clearTimeout(delay)
    }
    delay = setTimeout(()=>{
      let ra = this.data.ra;
      let rid = this.data.rid;
      let rq = this.data.rq;
      let rtext = this.data.rtext;
      let rtype = this.data.rtype;
      let openid = wx.getStorageSync('openid')
      if(ra.length == 0) {
        wx.showToast({
          title: '请输入你的解析',
          icon: 'none'
        })
        return ;
      }
      if(openid){
        DBCorrection.where({openid, rid, rq}).get()
        .then(
          rows=>{
            // console.log('1.0',rows)
            if(rows.data.length != 0) {
                wx.showToast({
                  title: '您已经提交过了，或者联系作者..',
                  icon: 'none'
                })
                this.setData({ show: false });
            }
            else {
              DBCorrection.add({data:{openid, rid, rq,ra,text:rtext, type: rtype}}).then(
                rows=>{
                  // console.log('2.0',rows);
                  if(rows.errMsg == "collection.add:ok") {
                     wx.showToast({
                       title: '提交成功。',
                       icon: 'none'
                     })
                  }
                }
              )
              .then(
                ()=>{
                  this.setData({ show: false });
                }
              )
            }
          }
        )
      }

      delay = null;
    },500)
    // console.log({rid,rq,ra});
  },
  showPopup() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  onChange(event) {
    // event.detail 为当前输入的值
    // console.log(event.detail);
    this.setData({
      ra: event.detail
    })
  },
})